package com.neteast.androidclient.newscenter.util;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class SinaWeiBoHelper {
	public static final String CONSUMER_KEY = "3353932868";
	public static final String CONSUMER_SECRET = "50955df914859f99aadf77f4455ea548";
	
	private static final String LOGOUT_URL="https://api.weibo.com/2/account/end_session.json";
	
	public static final int LOGOUT_SUCCESS = 6;
	public static final int LOGOUT_ERROR = 7;
	
	/**
	 * 退出新浪微博，暂时没有地方调用
	 * 	注，该方法不能接触绑定
	 * @param context
	 * @param handler
	 */
	public static void logout(final Context context,final Handler handler){
		new Thread(new Runnable() {
			@Override
			public void run() {
				Weibo weibo = Weibo.getInstance();
				WeiboParameters params=new WeiboParameters();
				params.add("source", Weibo.getAppKey());
				params.add("access_token", weibo.getAccessToken().getToken());
				String ret;
				try {
					ret = weibo.request(context, LOGOUT_URL, params, "GET",weibo.getAccessToken());
					Log.i("test", "ret="+ret);
					handler.sendEmptyMessage(LOGOUT_SUCCESS);
				} catch (WeiboException e) {
					handler.sendEmptyMessage(LOGOUT_ERROR);
					throw new RuntimeException(e.getMessage());
				}
			}
		}).start();
	}
	
	public static class AuthDialogListener implements WeiboDialogListener {
		private Context context;
		private Button button;
		
		public AuthDialogListener(Context context, Button button) {
			this.context = context;
			this.button = button;
		}

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			Log.i("test", "token="+token+"expires_in="+expires_in);
			AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			button.setText("已绑定");
			button.setEnabled(false);
			Toast.makeText(context, "绑定新浪微博成功", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(context,"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(context, "Auth cancel",Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			
		}
	}
}
